package com.ywu.file.sys.sdk.utils;

import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import com.ywu.file.sys.sdk.config.YwuFileSystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Objects;

/**
 * @ClassName BuildMssaHeaderUtil
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/9/28 11:35
 * @Version 1.0
 **/
@Component
@Slf4j
public class YfsBuildMssaHeaderUtil {
    @Autowired
    @Qualifier("ywuFileSystemRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private YwuFileSystemConfig config;

    public String buildAuthToken() {
        String appId = config.getAppId();
        String appToken = config.getAppToken();
        String source = config.getSource();
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("appId", appId);
        requestMap.put("appToken", appToken);
        requestMap.put("source", source);
        String body = GsonUtils.serialize(requestMap);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        //  调用接口构建token
        String resStr = restTemplate.postForObject(config.getDoGetTokenUrl(), entity, String.class);
        CommonResult commonResult = GsonUtils.deserialize(resStr, CommonResult.class);
        // 判断调用是否成功
        if (Objects.isNull(commonResult)) {
            return null;
        }
        if (commonResult.getCode().equals("200")) {
            return (String) commonResult.getData();
        }
        return null;
    }
}
